<%@ tag language="java" pageEncoding="UTF-8"%>
<%@ include file="/webpage/include/taglib.jsp"%>
<%@ attribute name="id" type="java.lang.String" required="true" description="编号"%>
<%@ attribute name="name" type="java.lang.String" required="true" description="隐藏域名称（ID）"%>
<%@ attribute name="relationName" type="java.lang.String" required="false" description="需要关联带入数据
格式：div的id(如果是金额类型的，加上/money),弹窗返回的对应的值名字(如果是对象，则为对象名.属性名),可传多个以‘|’分割
例如：modell,modell.name|price/money,price)"%>
<%@ attribute name="value" type="java.lang.String" required="true" description="隐藏域值（ID）"%>
<%@ attribute name="labelName" type="java.lang.String" required="true" description="输入框名称（Name）"%>
<%@ attribute name="labelValue" type="java.lang.String" required="true" description="输入框值（Value）"%>
<%@ attribute name="fieldLabels" type="java.lang.String" required="true" description="表格Th里显示的名字"%>
<%@ attribute name="fieldKeys" type="java.lang.String" required="true" description="表格Td里显示的值"%>
<%@ attribute name="searchLabels" type="java.lang.String" required="true" description="检索框标签"%>
<%@ attribute name="searchKeys" type="java.lang.String" required="true" description="检索框key"%>
<%@ attribute name="title" type="java.lang.String" required="true" description="选择框标题"%>
<%@ attribute name="url" type="java.lang.String" required="true" description="数据地址"%>
<%@ attribute name="cssClass" type="java.lang.String" required="false" description="css样式"%>
<%@ attribute name="cssStyle" type="java.lang.String" required="false" description="css样式"%>
<%@ attribute name="isMultiSelected" type="java.lang.Boolean" required="false" description="是否允许多选"%>
<%@ attribute name="disabled" type="java.lang.String" required="false" description="是否限制选择，如果限制，设置为disabled"%>
<%@ attribute name="btnAdd" type="java.lang.String" required="false" description="输入框最后边的图片样式"%>
<%@ attribute name="dialogTitle" type="java.lang.String" required="false" description="弹窗名字"%>
<%@ attribute name="dialogUrl" type="java.lang.String" required="false" description="弹窗名字"%>
<%@ attribute name="dialogWidth" type="java.lang.String" required="false" description="弹窗名字"%>
<%@ attribute name="dialogHeight" type="java.lang.String" required="false" description="弹窗名字"%>
<%@ attribute name="conDivIds" type="java.lang.String" required="false" description="动态关联的其他dom的id"%>
<input id="${id}Id" name="${name}"  type="hidden" value="${value}"/>
<div class="input-group" style="width: 100%">
	<input id="${id}Name"  name="${labelName }" ${allowInput?'':'readonly="readonly"'}  type="text" value="${labelValue}" data-msg-required="${dataMsgRequired}"
		   class="${cssClass}" style="${cssStyle}"/>
	<span class="input-group-btn">
	       		 <button type="button"  id="${id}Button" class="btn <c:if test="${fn:contains(cssClass, 'input-sm')}"> btn-sm </c:if><c:if test="${fn:contains(cssClass, 'input-lg')}"> btn-lg </c:if> btn-primary ${disabled} ${hideBtn ? 'hide' : ''}"><i class="fa ${btnAdd ? "fa-plus" : "fa-search"}"></i>
	             </button>
	               <button type="button" id="${id}DelButton" class="close" data-dismiss="alert" style="position: absolute; top: 5px; right: 53px; z-index: 999; display: block;">×</button>
       		 </span>

</div>
<label id="${id}Name-error" class="error" for="${id}Name" style="display:none"></label>
<script type="text/javascript">
	$(document).ready(function(){
		var b = "${btnAdd}";
		if(b != "" && b == "true"){
			$("#${id}Name").click(function(){
				if ($("#${id}Button").hasClass("disabled")){
					return true;
				}

				top.layer.open({
					type: 2,
					area: ['1500px', '1000px'],
					title:"${title}",
					auto:true,
					name:'friend',
					content: "${ctx}/tag/gridselect?url="+encodeURIComponent("${url}")+"&fieldLabels="+encodeURIComponent("${fieldLabels}")+"&fieldKeys="+encodeURIComponent("${fieldKeys}")+"&searchLabels="+encodeURIComponent("${searchLabels}")+"&searchKeys="+encodeURIComponent("${searchKeys}")+"&isMultiSelected=${isMultiSelected? true:false}",
					btn: ['确定', '关闭'],
					yes: function(index, layero){
						var iframeWin = layero.find('iframe')[0].contentWindow; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
						var items = iframeWin.getSelections();
						if(items == ""){
							jp.warning("必须选择一条数据!");
							return;
						}
						var ids = [];
						var names = [];
						for(var i=0; i<items.length; i++){
							var item = items[i];
							ids.push(item.id);
							names.push(item${fn:substring(labelName, fns:lastIndexOf(labelName, '.'), fn:length(labelName))})
						}
						$("#${id}Id").val(ids.join(","));
						$("#${id}Name").val(names.join(","));
						putRelName("${relationName}",item)
						if(typeof getSearch === 'function'){
							getSearch();
						}
						top.layer.close(index);//关闭对话框。
					},
					cancel: function(index){
					}
				});
			})

			$("#${id}Button").click(function(){
				jp.openSaveDialog('${dialogTitle}', "${ctx}${dialogUrl}",'${dialogWidth}', '${dialogHeight}');
			})

		}else {
			$("#${id}Button, #${id}Name").click(function(){

				if ($("#${id}Button").hasClass("disabled")){
					return true;
				}
                var url="${url}";
                var conDivIds="${conDivIds}";
				//自定义过滤条件
                if(conDivIds != undefined && conDivIds != ""){
                	var conDivIdArr = conDivIds.split("|");
                	for(var i=0; i<conDivIdArr.length; i++){
                		var param;
                		if(conDivIdArr[i].indexOf("_") > 0){
                			param = conDivIdArr[i].split("_")[1];
						}else {
							param = conDivIdArr[i];
						}
                		if(i==0){
                			url = url + "?" + param + "=" + $("#"+conDivIdArr[i]).val();
						}else {
							url = url + "&" + param + "=" + $("#"+conDivIdArr[i]).val();
						}
					}
				}
				top.layer.open({
					type: 2,
					area: ['2000px', '1500px'],
					title:"${title}",
					auto:true,
					name:'friend',
					content: "${ctx}/tag/gridselect?url="+encodeURIComponent(encodeURIComponent(url))+"&fieldLabels="+encodeURIComponent("${fieldLabels}")+"&fieldKeys="+encodeURIComponent("${fieldKeys}")+"&searchLabels="+encodeURIComponent("${searchLabels}")+"&searchKeys="+encodeURIComponent("${searchKeys}")+"&isMultiSelected=${isMultiSelected? true:false}",
					btn: ['确定', '关闭'],
					yes: function(index, layero){
						var iframeWin = layero.find('iframe')[0].contentWindow; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
						var items = iframeWin.getSelections();
						if(items == ""){
							jp.warning("必须选择一条数据!");
							return;
						}
						var ids = [];
						var names = [];
						for(var i=0; i<items.length; i++){
							var item = items[i];
							ids.push(item.id);
							names.push(item${fn:substring(labelName, fns:lastIndexOf(labelName, '.'), fn:length(labelName))})
						}
						$("#${id}Id").val(ids.join(","));
						$("#${id}Name").val(names.join(","));

						if(b == "search") {
							putRelName("${relationName}",item,true)
						}else {
							putRelName("${relationName}",item,false)
						}
						top.layer.close(index);//关闭对话框。
					},
					cancel: function(index){
					}
				});
			})
		}

		$("#${id}DelButton").click(function(){
			// 是否限制选择，如果限制，设置为disabled
			if ($("#${id}Button").hasClass("disabled")){
				return true;
			}
			// 清除
			$("#${id}Id").val("");
			$("#${id}Name").val("");
			$("#${id}Name").focus();

		});
	})

	/**
	 * @description name:传入的div的id，jb:弹窗检索返回的json对象。若div是金额类型的，自动转换金额格式
	 * @param name
	 * @param jb
	 */
	function putRelName(name,jb,b) {
		var b1 = false;
		if(name != ""){
			var names = name.split("|");
			$.each(names, function (index,value) {
				var k = value.split(",")[0];
				var v = value.split(",")[1];
				var vv = v.split(".");
				var kk = k.split("/");
				var val;

				if(vv.length > 1){
					if(jb[vv[0]] != null && jb[vv[0]] != undefined){
						val = jb[vv[0]][vv[1]];
					}
				}else {
					val = jb[v];
				}
				if(kk.length > 1){
					$('#'+kk[0]).val(jp.toFloat(val,2))
				}else {
					$('#'+k).val(val)
				}
				if(b){
				    if(k.indexOf("List") > -1){
                        var name1 = k.split("List")[1];
                        var idx = name1.split("_")[0];
                        getSearch(idx);
                    }else {
				    	b1 = true;
					}
				}
			})
			if(b1){
				getSearch();
			}
		}else {
			if(b) {
				getSearch();
			}
		}

	}
</script>
